import { useUpdate } from "ahooks";
import { useRef } from "react";

/**
 * antd table组件简易勾选hook
 *
 * api说明
 * fn?: (selectedKeys: React.Key[], selectedData: any[]) => void
 * 支持传入一个函数，在勾选后做另外的操作,该函数会传入选择的key，及选择的行数据
 */
const useTableCheck = (fn?: (selectedKeys: React.Key[], selectedData: any[]) => void) => {
  // 刷新hook
  const update = useUpdate();
  // 选择的key
  const selectedRowKeys = useRef<React.Key[]>([]);
  // 选择的数据
  const selectedRows = useRef<any[]>([]);

  // 选择的行变化
  const selectRowChange = (selectedKeys: React.Key[], selectedData: any[]) => {
    selectedRowKeys.current = selectedKeys;
    selectedRows.current = selectedData;
    update();
    fn?.(selectedKeys, selectedData);
  };

  // 清除勾选
  const clearRowChecked = () => {
    selectedRowKeys.current = [];
    selectedRows.current = [];
    update();
  };

  // 设置勾选
  const setRowChecked = (selectedKeys: React.Key[], selectedData: any[]) => {
    selectedRowKeys.current = selectedKeys;
    selectedRows.current = selectedData;
    update();
  };

  return {
    rowSelection: {
      selectedRowKeys: selectedRowKeys.current,
      onChange: selectRowChange
    },
    selectedRowKeys: selectedRowKeys.current,
    selectedRows: selectedRows.current,
    clearRowChecked,
    setRowChecked,
  } as const
};

export default useTableCheck;
